package com.apobates.forum.orize.spring;

import com.apobates.forum.orize.core.OrizeMemberRolePredicate;
import com.apobates.forum.orize.spring.boot.OrizeProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 实现Orize过滤器
 * @author xiaofanku@live.cn
 * @since 20210821
 */
public class OrizeAuthSpringInterceptorImpl extends HandlerInterceptorAdapter {
    @Autowired
    private OrizeAuthHelper orizeAuthHelper;
    @Autowired
    private OrizeMemberRolePredicate memberRolePredicate;
    @Autowired
    private OrizeProperties orizeProperties;

    /**
     * 预处理回调方法，实现处理器的预处理（如检查登陆），第三个参数为响应的处理器，自定义Controller
     * 返回值：true表示继续流程（如调用下一个拦截器或处理器）；false表示流程中断（如登录检查失败），不会继续调用其他的拦截器或处理器，此时我们需要通过response来产生响应；
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws java.lang.Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ImmutablePair<Boolean, Map> ips = orizeAuthHelper.verify(memberRolePredicate, request);
        boolean mr = ips.getLeft();
        Map mrm = ips.getRight();
        //
        if(!mr){
            String redirectPath = request.getContextPath() + StringUtils.defaultString(orizeProperties.getLogPath(), "/orize/result");
            /*
            FlashMap flashMap = new FlashMap();
            flashMap.put("errors", mrm.get("message"));
            flashMap.put("method", mrm.get("reqMethod"));
            flashMap.put("path", mrm.get("reqPath"));
            flashMap.setTargetRequestPath(redirectPath);
            FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
            flashMapManager.saveOutputFlashMap(flashMap, request, response);*/
            response.sendRedirect(redirectPath);
            return false;
        }
        return true;
    }

}
